package com.swang.pms.common.util;

import java.lang.reflect.Method;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: EnumToDataUtil
 * @Description: 泛型类，处理枚举数据
 * @author: 王泽
 * @date: 2017年3月16日 下午9:45:51
 */
public class EnumToDataUtil {

    private static final Logger log = LoggerFactory.getLogger(EnumToDataUtil.class);

    public static String getDHEnumsValuesFromEnum(Class<?> clazz) {
        Map map = new HashMap();
        try {
            Method[] methods = clazz.getDeclaredMethods();
            if (clazz.isEnum()) {
                List<?> list = Arrays.asList(clazz.getEnumConstants());
                for (Object object : list) {
                    StringBuffer key = new StringBuffer("");
                    StringBuffer value = new StringBuffer("");
                    for (Method method : methods) {
                        if (method.getName().startsWith("getCode")) {
                            key.append(method.invoke(object));
                        }
                        if (method.getName().startsWith("getName")) {
                            value.append(method.invoke(object));
                        }
                    }
                    if (!"".equals(key.toString())) {
                        map.put(key.toString(), value.toString());
                    }
                }
            }
        } catch (Exception e) {
            log.error("枚举类转化成dhtmlx串失败！", e);
        }
        return getDHEnumsValuesByMap(map, "", "");
    }

    public static String getDHEnumsValuesByMap(Map map, String selectValue, String selectText) {
        if (map == null || map.isEmpty()) {
            return "([[\'" + selectValue + "\', \'" + selectText + "\']])";
        }
        StringBuffer returnStr = new StringBuffer("([[\'" + selectValue + "\', \'" + selectText + "\'],");
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            returnStr.append("[\'");
            returnStr.append(entry.getKey());
            returnStr.append("\',\'");
            returnStr.append(entry.getValue());
            returnStr.append("\']");
            if (iter.hasNext()) {
                returnStr.append(",");
            }
        }
        returnStr.append("])");
        return returnStr.toString();
    }

}
